package top.yongyan0624.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.yongyan0624.common.dto.PassDto;
import top.yongyan0624.common.lang.Const;
import top.yongyan0624.common.lang.Result;
import top.yongyan0624.entity.Nanny;
import top.yongyan0624.entity.SysRole;
import top.yongyan0624.entity.SysUser;
import top.yongyan0624.entity.SysUserRole;
import top.yongyan0624.utils.OSSUtils;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-08-15
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {
    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    /**
     * 注册普通用户账号
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/register")
    public Result register(@Validated @RequestBody SysUser sysUser) {
        SysUser u = sysUserService.getByUsername(sysUser.getUsername());
        if (u != null) {
            return Result.fail("注册失败，用户用户名重复");
        }

        // 加密密码
        String password = passwordEncoder.encode(sysUser.getPassword());
        sysUser.setPassword(password);

        // 默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);

        sysUserService.save(sysUser);

        return Result.success(sysUser);
    }

    /**
     * 直接注册公司账号
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/company/register")
    public Result companyRegister(@Validated @RequestBody SysUser sysUser) {
        SysUser u = sysUserService.getByUsername(sysUser.getUsername());
        if (u != null) {
            return Result.fail("注册失败，公司账号名重复");
        }

        // 加密密码
        String password = passwordEncoder.encode(sysUser.getPassword());
        sysUser.setPassword(password);

        // 账号类型
        sysUser.setType(1);
        // 默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);

        //存储账号
        sysUserService.save(sysUser);

        //公司账号注册成功后，为这个账号授权，拥有后台管理界面的权限
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(sysUser.getId());
        userRole.setRoleId(6L);
        sysUserRoleService.save(userRole);

        return Result.success(sysUser);
    }

    /**
     * 用户账号升级为公司账号（此时已经登录成功）
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/upgrade/register")
    public Result upgradeRegister(@Validated @RequestBody SysUser sysUser) {
        SysUser u = sysUserService.getById(sysUser.getId());
        if (u == null) {
            return Result.fail("升级失败，当前用户账号不存在");
        }
        u = sysUserService.getByUsername(sysUser.getUsername());
        if (u != null) {
            return Result.fail("升级失败，公司账号名重复");
        }
        //用户账号升级为公司账号（此时已经登录成功）

        // 加密密码
        String password = passwordEncoder.encode(sysUser.getPassword());
        sysUser.setPassword(password);

        // 默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);

        //初始化公司基本数据，并更新
        sysUser.setSex("");
        sysUser.setAge(-1);
        sysUser.setType(1);
        sysUserService.updateById(sysUser);

        //公司账号注册成功后，为这个账号授权，拥有后台管理界面的权限
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(sysUser.getId());
        userRole.setRoleId(6L);
        sysUserRoleService.save(userRole);

        return Result.success(sysUser);
    }

    @PostMapping("/modify")
    public Result modify(@Validated @RequestBody SysUser sysUser) {
        sysUserService.updateById(sysUser);
        return Result.success(sysUser);
    }

    @PostMapping("/modifyAvatar/{id}")
    public Result modifyAvatar(@PathVariable("id") Long id, MultipartFile avatar) {
        SysUser user;
        try {
            if (avatar.isEmpty()) {
                return Result.fail("头像路径为空");
            }

            //获取当前用户
            user = sysUserService.getById(id);

            //存储文件，同时获取图片URL
            String url = OSSUtils.getImgUrl(avatar);

            //设置用户头像URL
            user.setAvatar(url);
            sysUserService.updateById(user);

        } catch (IllegalStateException e) {
            e.printStackTrace();
            return Result.fail("头像上传失败！");
        }
        return Result.success(user);
    }

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result info(@PathVariable("id") Long id) {

        SysUser sysUser = sysUserService.getById(id);
        Assert.notNull(sysUser, "找不到该管理员");

        List<SysRole> roles = sysRoleService.listRolesByUserId(id);
        sysUser.setRoles(roles);
        return Result.success(sysUser);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result list(String username) {

        Page<SysUser> pageData = sysUserService.page(getPage(), new QueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(username), "username", username)
                .eq("type", 0));

        pageData.getRecords().forEach(u -> {
            u.setRoles(sysRoleService.listRolesByUserId(u.getId()));
        });

        return Result.success(pageData);
    }

    @GetMapping("/companyList")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result companyList(String username) {

        Page<SysUser> pageData = sysUserService.page(getPage(), new QueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(username), "username", username)
                .eq("type", 1));

        pageData.getRecords().forEach(u -> {
            u.setRoles(sysRoleService.listRolesByUserId(u.getId()));
        });

        return Result.success(pageData);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result save(@Validated @RequestBody SysUser sysUser) {
        // 默认密码
        String password = passwordEncoder.encode(Const.DEFULT_PASSWORD);
        sysUser.setPassword(password);

        // 默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);

        sysUserService.save(sysUser);
        return Result.success(sysUser);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result update(@Validated @RequestBody SysUser sysUser) {
        sysUserService.updateById(sysUser);
        return Result.success(sysUser);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@RequestBody Long[] ids) {

        sysUserService.removeByIds(Arrays.asList(ids));
        //删除所有与这些用户有关联的记录
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id", ids));
        nannyService.remove(new QueryWrapper<Nanny>().in("user_id", ids));

        return Result.success("删除用户成功");
    }

    @Transactional
    @PostMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result rolePerm(@PathVariable("userId") Long userId, @RequestBody Long[] roleIds) {

        List<SysUserRole> userRoles = new ArrayList<>();

        Arrays.stream(roleIds).forEach(r -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);

            userRoles.add(sysUserRole);
        });

        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUserRoleService.saveBatch(userRoles);

        // 删除缓存
        SysUser sysUser = sysUserService.getById(userId);
        sysUserService.clearUserAuthorityInfo(sysUser.getId());

        return Result.success("用户角色设定成功");
    }

    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public Result repass(@RequestBody Long userId) {

        SysUser sysUser = sysUserService.getById(userId);

        sysUser.setPassword(passwordEncoder.encode(Const.DEFULT_PASSWORD));

        sysUserService.updateById(sysUser);
        return Result.success("密码重置成功：888888");
    }

    @PostMapping("/updatePass")
    public Result updatePass(@Validated @RequestBody PassDto passDto, Principal principal) {

        SysUser sysUser = sysUserService.getByUsername(principal.getName());

        boolean matches = passwordEncoder.matches(passDto.getCurrentPass(), sysUser.getPassword());
        if (!matches) {
            return Result.fail("旧密码不正确");
        }

        sysUser.setPassword(passwordEncoder.encode(passDto.getPassword()));

        sysUserService.updateById(sysUser);
        return Result.success("修改密码成功");
    }
}
